/*
 * 获取Oauth登陆数据
 */
package com.office.commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class OauthServer {

	public String getOauthInfo(String code, String appkey, String appsecret,
			String redirectUrlPrefix) throws NoSuchAlgorithmException,
			KeyManagementException, IOException {
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(X509Certificate[] certs,
					String authType) {
			}

			public void checkServerTrusted(X509Certificate[] certs,
					String authType) {
			}
		} };

		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

		URL url = new URL(
				"https://oauth.taobao.com/token?grant_type=authorization_code&client_id="
						+ appkey + "&client_secret=" + appsecret + "&code="
						+ code + "&redirect_uri=" + redirectUrlPrefix);
		 
		HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url
				.openConnection();
		httpsURLConnection.setConnectTimeout(30000);
		httpsURLConnection.setReadTimeout(30000);
		httpsURLConnection.setDoOutput(true);
		httpsURLConnection.setDoInput(true);
		httpsURLConnection.setUseCaches(false);
		httpsURLConnection.setRequestMethod("POST");

		httpsURLConnection.connect();

		int responseCode = httpsURLConnection.getResponseCode();
		InputStream input = null;
		if (responseCode == 200) {
			input = httpsURLConnection.getInputStream();
		} else {
			input = httpsURLConnection.getErrorStream();
		}
		BufferedReader in = new BufferedReader(new InputStreamReader(input));
		StringBuilder result = new StringBuilder();
		String line = null;
		while ((line = in.readLine()) != null) {
			result.append(line);
		}
		System.out.println( result.toString());
		return result.toString();
	}
}
